package team02.server.model;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;

public abstract class MySQLModel implements Model {
	/**
	 * 団体のテーブル
	 */
	public static final String TABLE_ORG = "jp_organization";
	/**
	 * 　回答のテーブル
	 */
	public static final String TABLE_ANSWER = "jp_answer";
	/**
	 * テストのテーブル
	 */
	public static final String TABLE_TEST = "jp_test";
	/**
	 * ユーザのテーブル
	 */
	public static final String TABLE_USER = "jp_user";
	/**
	 * 質問のテーブル
	 */
	public static final String TABLE_QUESTION = "jp_question";
	/**
	 * 受験者のテーブル
	 */
	public static final String TABLE_EXAMINEE = "jp_examinee";
	private static boolean isClassNotFound;

	protected Connection connection;
	protected Statement statement;
	protected ResultSet resultSet;
	private static final String CONNECTION_STRING = "jdbc:mysql://localhost:3306/jp_autotest?useUnicode=true&characterEncoding=UTF-8";
	private static final String MYSQL_USER = "team02";
	private static final String MYSQL_PASSWORD = "team02";;

	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			isClassNotFound = true;
		}
	}

	public MySQLModel(Connection connection) {
		super();
		this.connection = connection;
	}

	/**
	 * データ·ベースを維持するための接続
	 * 
	 * @return コネクション
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	protected void initConnection() throws SQLException {
		if(connection != null) return;
		if (isClassNotFound) throw new SQLException("Driver not found");
		connection = DriverManager.getConnection(CONNECTION_STRING, MYSQL_USER, MYSQL_PASSWORD);
	}

	protected void executeQuery(String query) throws SQLException {
		statement = connection.createStatement();
		this.resultSet = statement.executeQuery(query);
	}

	protected ResultSet executeQuery(String query, boolean isReturn) throws SQLException {
		statement = connection.createStatement();
		return statement.executeQuery(query);
	}

	protected int executeUpdate(String updateQuery) throws SQLException {
		statement = connection.createStatement();
		return statement.executeUpdate(updateQuery);
	}

	public void freeResources() throws SQLException {
		if (resultSet != null) {
			resultSet.close();
			resultSet = null;
		}
		if (statement != null) {
			statement.close();
			statement = null;
		}
		if (connection != null) {
			if(!connection.getAutoCommit()) return;//need to commit first
			connection.close();
			connection = null;
		}
	}

	public abstract int load() throws SQLException;

	public abstract int save() throws SQLException;

	public abstract int insert() throws SQLException;

	public abstract int delete() throws SQLException;

	public abstract void clear();

}
